import { asyncRouterMap, constantRoutes } from '@/router'
import store from '@/store'

/**
 * khl 优化:根据后台返回的菜单列表动态处理,消除前端写死的路由
 * @param  {Array} userRouter 后台返回的用户菜单列表
 * @param  {Array} allRouter  前端配置好的所有动态路由的集合
 * @return {Array} realRoutes 过滤后的路由
 */

export function recursionRouter(userRouter = [], allRouter = []) {
  const realRoutes = []
  let route404 = null
  for (let i = 0; i < allRouter.length; i++) {
    const v = allRouter[i]
    if (v.path === '*') {
      route404 = v
    } else {
      for (let j = 0; j < userRouter.length; j++) {
        const item = userRouter[j]
        if (v.path !== '*' && item.url === v.path && hasAuthority(v.meta.role)) {
          if (item.children && item.children.length > 0) {
            v.children = recursionRouter(item.children, v.children)
          }
          v.meta.title = item.name
          v.meta.icon = item.icon
          realRoutes.push(v)
        }
      }
    }
  }
  if (route404 !== null) {
    realRoutes.push(route404)
  }
  return realRoutes
}

function hasAuthority(roles) {
  if (undefined === roles) {
    return true
  }
  let has = false
  let end = false
  for (let i = 0; i < roles.length; i++) {
    const role = roles[i]
    if (role.substring(0, 5) === 'ROLE_') {
      for (let j = 0; j < store.getters.roleList.length; j++) {
        if (store.getters.roleList[j].code === role) {
          has = true
          end = true
          break
        }
      }
    }
    if (end) {
      break
    }
  }
  return has
}

/**
 *
 * @param {Array} routes 用户过滤后的路由
 *
 * 递归为所有有子路由的路由设置第一个children.path为默认路由
 */
export function setDefaultRoute(routes) {
  routes.forEach((v, i) => {
    if (v.children && v.children.length > 0) {
      v.redirect = { name: v.children[0].name }
      setDefaultRoute(v.children)
    }
  })
}

const permission = {
  state: {
    routers: constantRoutes, // 这是默认权限列表 比如404 500等路由
    dynamicRouters: [] // 这是通过后台获取的权利列表
  },
  mutations: {
    SET_ROUTERS: (state, routers) => {
      state.dynamicRouters = routers
      state.routers = constantRoutes.concat(routers)
    }
  },
  actions: {
    GenerateRoutes({ commit }, data) {
      return new Promise(resolve => {
        // 把传进来的menus 列表。用recursionRouter方法进行递归遍历出来，存入vuex中
        const routes = recursionRouter(data, asyncRouterMap)
        // 避免动态路由页面刷新后跳转404,
        // 参考：https://blog.csdn.net/qq_37121488/article/details/88287066
        routes.push({
          path: '*',
          redirect: '/404'
        })
        commit('SET_ROUTERS', routes)
        resolve()
      })
    }
  }
}

export default permission
